package com.zzl.bonds.ticket.untils;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author szsw
 * @date 2021/12/31 13:17:20
 */
public class StrUtils {

    private static final Pattern LINE_PATTERN = Pattern.compile("_(\\w)");
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    private StrUtils() {
    }

    /**
     * 驼峰转下划线
     *
     * @param str 驼峰字符串
     * @return 下划线字符串
     */
    public static String humpToLine(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 下划线转驼峰
     *
     * @param str 下划线符串
     * @return 驼峰字符串
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 首字母大写
     *
     * @param target 目标字符串
     * @return 首字母大写字符串
     */
    public static String capitalize(String target) {
        return changeFirstCharacterCase(target, true);
    }

    /**
     * 首字母小写
     *
     * @param target 目标字符串
     * @return 首字母小写字符串
     */
    public static String uncapitalize(String target) {
        return changeFirstCharacterCase(target, false);
    }

    /**
     * 修改首字母成大写或小写
     *
     * @param target     目标字符串
     * @param capitalize 是否大写（true：首字母大写；false：首字母小写）
     * @return 处理后字符串
     */
    private static String changeFirstCharacterCase(String target, boolean capitalize) {
        if (!hasLength(target)) {
            return target;
        }

        char baseChar = target.charAt(0);
        char updatedChar;
        if (capitalize) {
            updatedChar = Character.toUpperCase(baseChar);
        } else {
            updatedChar = Character.toLowerCase(baseChar);
        }
        if (baseChar == updatedChar) {
            return target;
        }

        char[] chars = target.toCharArray();
        chars[0] = updatedChar;
        return new String(chars, 0, chars.length);
    }

    /**
     * 字符串是否存在长度
     *
     * @param target 目标字符串
     * @return 是否有长度
     */
    public static boolean hasLength(String target) {
        return (target != null && !target.isEmpty());
    }

    /**
     * 格式化 double类型 数据成指定 财务格式 3位加逗号
     * @param value
     * @return
     */
    public static String simgleFormat(double value) {
        //实例化DecimalFormat
        DecimalFormat myFormat = new DecimalFormat("#,##0.00");
        return myFormat.format(value);//将数字进行格式化
    }

}
